from django.template.smartif import infix
from rest_framework import serializers

from apps.inform.models import *
from apps.oaauth.serializers import *

class InformReadSerializer(serializers.ModelSerializer):
    class Meta:
        model = InformRead
        fields = '__all__'

class InformSerializer(serializers.ModelSerializer):
    author = UserSerializer(read_only=True)
    departments = DepartmentSerializer(read_only=True, many=True)
    department_ids = serializers.ListField(write_only=True)
    reads = InformReadSerializer(read_only=True, many=True)

    class Meta:
        model = Inform
        fields = '__all__'
        read_only_fields = ('public',)
    def create(self, validated_data):
        request = self.context.get('request')
        department_ids = validated_data.pop('department_ids')
        user = request.user
        # department_ids = [int(did) for did in department_ids]
        department_ids = list(map(lambda value: int(value), department_ids))
        if 0 in department_ids:
            inform = Inform.objects.create(public=True, author=user, **validated_data)
        else:
            departments = OADepartment.objects.filter(id__in=department_ids).all()
            # if not departments or len(departments) != len(department_ids):
            #     raise serializers.ValidationError("部门编号输入有误")
            inform = Inform.objects.create(public=False, author=user, **validated_data)
            inform.departments.set(departments)
            inform.save()
        return inform

class ReadInformSerializer(serializers.Serializer):
    inform_pk = serializers.IntegerField(error_messages={
        "required":"请传入inform的id!"
    })
    class Meta:
        fields = '__all__'

